<template>
    <div class="wrapper">
        <div class="banner">
            <img src="http://file.rzkeji.com/web/dang/question_banner.png">
        </div>
        <div class="content">
            <div class="title">
                <div class="tit">{{question_package_name}}</div>
            </div>
            <div class="qrcode_wrapper" v-show="flag">
                <img :src="qrcode_url" />
                <p style="font-size: 0.5rem">用微信扫一扫扫描上述二维码即可参与作答哦</p>
            </div>

            <div class="count" v-show="!flag && !isStartAnswer">
                {{count}}
            </div>

            <div class="answer_wrapper" v-show="flag">
                <button class="answer" @click="startAnswer()">开始答题</button>
            </div>

            <div style="margin-top: 12px;width: 100%;text-align: center" v-show="isStartAnswer">
                <span style="font-size: 15px;color: white">{{msg}}</span>
                <span style="font-size: 20px;color: #ffd3b3;font-weight: bold">{{toNextTime}}</span>
            </div>

            <div class="answer_list" v-show="isStartAnswer">
                <ul>
                    <li  v-for="(answer,index) in answerList" :key="index">{{answer.answer}}</li>
                </ul>
            </div>

            <ul class="man_item_list" v-if="userList.length > 0">
                <li v-for="(userinfo,index) in userList" :key="index" class="man_item">
                    <div><img :src="userinfo.photo_url"></div>
                    <div>{{userinfo.score}}分</div>
                    <!-- <div>{{userinfo.score}}</div>          -->
                </li>
            </ul>

            <div style="color: orange;width: 100%;text-align: center;padding:10px 0;font-size: 0.5rem">
              已加入人数：{{joinUserNum}}人
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: "question",
      data(){
          return {
			  id:'',
              websock:"",
              client_id:"",
              question_package_name:"",
              qrcode_url:"",
              userList:[],
              delClientId:"",
              count:5,
              flag:true,
              questionList:[],
              answerList: ['我吃了', '没吃', '你别问了'],
              isStartAnswer:false,
              toNextTime:15,
              readAnswerTime:3,
              allQuestionNum:0,
              theQuestionNum:0,
              key:"",
              qp_id: "",
              msg:"答题倒计时：",
              rightNum:"",
              joinUserNum:0
          }
      },
      computed: {
          answerIng(){
              if(this.count==10){
                  return true
              }else{
                  return false
              }
          }
      },

      methods:{
         initWebSocket(){ //初始化weosocket
		 let This=this
          // const wsuri = `ws://120.78.180.137:8282`
		  const wsuri='wss://api.rzkeji.com'
		  uni.connectSocket({
		  	url: wsuri,
		  	success() {
		  		console.log('连接成功')
		  		This.initEventHandle()
		  	}
		  });

        },
		initEventHandle(){
			var This = this;
			uni.onSocketMessage(function(res){
				This.websocketonmessage(res)
			});

			uni.onSocketOpen(function (res) {
				console.log('socket链接打开');
			});
			uni.onSocketClose(function (res) {
				console.log('WebSocket断开！',);
			});
			uni.onSocketError(function (res) {
				console.log('WebSocket连接错误！');
				// This.reconnect()
			});
		},
        websocketonopen(){ //连接建立之后执行send方法发送数据
          // this.websocketsend(this.user)
        },
        websocketonerror(){//连接建立失败重连
          this.initWebSocket()
        },
        websocketonmessage(e){
            let _this = this //数据接收
            // var data = eval("("+e.data+")");
			var data=JSON.parse(e.data)
            var handle = data.handle || '';
            if(handle != "" && handle=="init"){
                _this.client_id=data.client_id
                _this.serverOnLine()
            }else if(handle != "" && handle=="user_online"){
                var user_info = data.user_info || '';
                if(_this.userList.length<50){
                    //判断用户已经存在列表当中，存在就不再往用户数组添加 hao
                    let someFlag = _this.userList.some(element => {
                        return element.id == user_info.id;
                    });
                    if(!someFlag){
                        _this.userList.push(user_info)
                    }
                    _this.joinUserNum = _this.userList.length
                }
            }else if(handle != "" && handle=="logout"){
                _this.delClientId = data.client_id
                _this.delUser()
            }
        },
        websocketsend(Data){//数据发送
          // this.websock.send(Data)
        },
        websocketclose(e){  //关闭
          console.log('断开连接', e)
        },
        async serverOnLine(){
			let params={
				"client_id":this.client_id,
				"device_num":"sz00001",
				"qp_id":this.id
			}
            let res=await this.$api.serverOnline(params)
            if(res.data.level == "success"){
                let data = res.data.data
                this.question_package_name = data.question_package.name
                this.qrcode_url = data.qrcode_url
                this.qp_id      = data.question_package.id
                this.key        = data.key
            }else {
                uni.showToast({
                	icon:'none',
					message:res.data.message
                })
            }
        },
        delUser(){
            for (let i = 0;i < this.userList.length;i++) {
                let obj = this.userList[i];
                if (obj.client_id == this.delClientId) {
                    this.userList.splice(i, 1);
                }
                this.joinUserNum = this.userList.length
            }
        },
        async startAnswer(){
            if(this.userList.length == 0){
                uni.showToast({
                	icon:'none',
                	title:'暂无人员加答题'
                })
                return
            }
            this.flag=false
            // this.$axios发送请求，请求答题
			let params={
					qp_id:this.qp_id,
					"key":this.key,
				}

            let res=await this.$api.getQuestionsList(params)
            if(res.data.level == "success"){
                this.questionList = res.data.data;
                this.allQuestionNum = res.data.data.length
                this.$store.dispatch('_setAllQuestionNum',res.data.data.length);
                const countDown = setInterval(()=>{
                    this.count--
                    if(this.count == 0){
                        clearInterval(countDown)
                        this.count="开始"
                        this.isStartAnswer=true
                        this.startTimeToNext()
                    }
                },1000)
            }else {
                uni.showToast({
                	icon:'none',
                	title:res.data.message
                })
            }
        },
          async startTimeToNext(){
              this.sendToClientStart();
              let qid = this.questionList[this.theQuestionNum].id
              let res=await this.$api.getQuestionAnswers({'q_id':qid})
              if(res.data.level == "success"){
                  this.question_package_name = "题目"+(parseInt(this.theQuestionNum) + 1)+"："+this.questionList[this.theQuestionNum].question;
                  this.question_package_name = this.question_package_name + "("+this.questionList[this.theQuestionNum].score+"分)"
                  this.answerList = res.data.data;
                  this.rightNum   = res.data.right_num
              }else {
                  uni.showToast({
                  	icon:'none',
                  	message:res.data.message
                  })
              }

            const countDownNext = setInterval(()=>{
                this.toNextTime--
                if(this.toNextTime == 0){
                    clearInterval(countDownNext)
                    this.startTimeToReadAnswer()
                }
            },1000)
        },
          startTimeToReadAnswer(){
                this.theQuestionNum++
                this.msg = "正确答案是："
                this.toNextTime = this.rightNum
                // this.getRankList();
                const countDownRead = setInterval(()=>{
                    this.readAnswerTime--
                    this.getRankList();
                    if(this.readAnswerTime == 0){

                        clearInterval(countDownRead)
                        this.readAnswerTime = 3
                        if(this.theQuestionNum < this.allQuestionNum){
                            this.msg = "答题倒计时："
                            this.toNextTime = 15
                            this.startTimeToNext()
                        }else{
                            this.toRankPage(this.key)
                        }
                    }
                },1000)
          },
          async sendToClientStart(){
              let qid = this.questionList[this.theQuestionNum].id;

			  let params={
				  'q_id':qid,
				  "key":this.key
			  }
              let res=await this.$api.startActive(params)
          },
        async getRankList(){
			//获取排行榜
			let params={
				'key':this.key
			}

          let res=await this.$api.getUsersScore(params)
          if(res.data.level == "success"){
            this.userList = res.data.data
          }else {
            uni.showToast({
            	icon:'none',
            	message:res.data.message
            })
          }
        },
        arrSort(arr){//降序
            const newArr= arr.sort((a,b)=>{
                return Number(b)-Number(a)
            })
            return newArr


        },
          toRankPage(key){
			  //跳转排行榜页面
			  uni.navigateTo({
			  	url:`/pages/answerRank/answerRank?key=${key}`
			  })
          },
      },
      onLoad(options){
		  this.id=options.id;
		  this.initWebSocket()
      },
      onHide(){
      	console.log('onHide')
      	uni.closeSocket();
      },
      onUnload(){
      	console.log('onUnLoad')
      	uni.closeSocket();
      },
    }
</script>

<style scoped lang="scss">
    .wrapper{
        width:100%;
        min-height: 100vh;
        /*background: url('http://file.rzkeji.com/web/dang/small_backgroud.jpg');*/
        background-color: #d40c14;
        background-size: 100% 100%;
    }

    .content{
        /*padding-top: 0.3rem;*/
    }

    .banner{
        width: 100%;
    }

    .banner img{
        width: 100%;
    }

    .title{
        margin: 0 auto;
        width: 75%;
        height: 100%;
        /*background: url("http://file.rzkeji.com/web/dang/q_name.png");*/
        /*background-size: 100% 100%;*/
    }

    .tit{
        text-align: center;
        padding: 40rpx;
        font-size: 28rpx;
        color:white;
    }

    .qrcode_wrapper{
        margin-top: 20rpx;
        width:100%;
        text-align: center;
		img{
			width: 240rpx;
			height: 240rpx;
		}
    }
    .qrcode_wrapper p{
        margin-top: 10px;
        color: white;
    }
    .count{
		background-color: orange;
		border-radius: 50%;
		width: 200rpx;
		height: 200rpx;
		line-height: 200rpx;
		margin: 0 auto;
		margin-top: 30rpx;
		font-size: 100rpx;
		text-align: center;
		color: white
		}
    .question{
        font-size: 30px;
        text-align: center;
        margin-top:20px;
        width:calc(100% - 80px);
        margin-left:40px;
        background:#fff;
        border:1px solid #fff;
    }
    .answer_wrapper{
        width:100%;
        text-align: center;
        margin-top:40rpx;
    }
    .answer_wrapper button{
        background-color: orange;
        font-size: 28rpx;
        width: 250rpx;
        padding: 10rpx;
        border-radius: 10rpx;
        color: white;
        border: none;
    }
    .answer_list{
		ul{
			margin-top: 24rpx;color: white;
			li{
				margin: 20px auto;
				border: 2rpx solid orange;
				text-align: center;
				font-size: 28rpx;
				width: 70%;
				padding: 20rpx
			}
		}
	}

    .man_item_list{
        display: flex;
        flex-wrap: wrap;
        margin-top:0.2rem;
        padding: 0 20rpx;
        color:#fff;
        font-size: 24rpx
    }
    .man_item{
        text-align: center;
        margin:10px;
    }
    .man_item div{
        width: 100%;
    }
    .man_item img{
        width:100rpx;
        height: 100rpx;
        object-fit:cover;
        border-radius: 50%;
    }

    .answering{
        color:#eee;
    }
</style>
